package model

import (
	"errors"
)

type SmartEncrypter struct {
	Rules map[string]*EncryptRule
}

func (s *SmartEncrypter) Init(rules []*EncryptRule) {
	if s.Rules == nil {
		s.Rules = make(map[string]*EncryptRule)
	}
	for _, rule := range rules {
		rule.Init()
		s.Rules[rule.Name] = rule
	}
}

func (g *SmartEncrypter) Match(value interface{}) string {
	for k, v := range g.Rules {
		if v.Match(value) {
			return k
		}
	}
	return "-"
}

func (g *SmartEncrypter) HandleByRule(name string, value interface{}) (interface{}, error) {
	if rule, ok := g.Rules[name]; ok {
		return rule.Handle(value)
	}
	return nil, errors.New("no such handle rule")
}

func (g *SmartEncrypter) HandleVersaByRule(name string, value interface{}) (interface{}, error) {
	if rule, ok := g.Rules[name]; ok {
		if rule.SupportDecrpt() {
			return rule.HandleVersa(value)
		} else {
			return nil, errors.New("rule not support decrypt")
		}
	}
	return nil, errors.New("no such handle rule")
}

//AddOrUpdate 添加或更新规则
func (s *SmartEncrypter) AddOrUpdate(rule *EncryptRule) {
	if s.Rules == nil {
		s.Rules = make(map[string]*EncryptRule)
	}
	s.Rules[rule.Name] = rule
	rule.Init()
}

func (s *SmartEncrypter) DeleteById(id int64) {
	for k, v := range s.Rules {
		if v.Id == id {
			delete(s.Rules, k)
			return
		}
	}
	return
}

func (s *SmartEncrypter) DisableById(id int64) {
	for _, v := range s.Rules {
		if v.Id == id {
			v.Disabled = true
			return
		}
	}
	return
}

func (s *SmartEncrypter) EnableById(id int64) {
	for _, v := range s.Rules {
		if v.Id == id {
			v.Disabled = false
			return
		}
	}
	return
}
